import request from './request'
import { ElMessage } from 'element-plus'

// 分页获取专辑列表
export const getAlbumPage = async (pageNum, pageSize, query = {}) => {
  try {
    const response = await request({
      url: '/album/page',
      method: 'GET',
      params: { pageNum, pageSize, ...query },
    })
    return response
  } catch (error) {
    ElMessage.error('获取专辑列表失败')
    return { success: false, message: error.message }
  }
}

// 通过ID获取专辑详情
export const getAlbumById = async (albumId) => {
  try {
    const response = await request({ url: `/album/${albumId}`, method: 'GET' })
    return response
  } catch (error) {
    ElMessage.error('获取专辑详情失败')
    return { success: false, message: error.message }
  }
}

// 创建专辑
// 注意: API期望multipart/form-data格式，请求参数应为FormData
export const createAlbum = async (albumData, onUploadProgress = () => {}) => {
  try {
    const response = await request({
      url: '/album',
      method: 'POST',
      data: albumData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress,
    })
    return response
  } catch (error) {
    console.error('创建专辑API调用失败:', error)
    return { success: false, message: error.message || '创建专辑失败' }
  }
}

// 更新专辑
export const updateAlbum = async (albumId, albumData) => {
  try {
    const response = await request({ url: `/album/${albumId}`, method: 'PUT', data: albumData })
    if (response.success) {
      ElMessage.success('更新专辑成功')
    } else {
      ElMessage.error(response.message || '更新专辑失败')
    }
    return response
  } catch (error) {
    ElMessage.error('更新专辑失败')
    return { success: false, message: error.message }
  }
}

// 添加音乐到专辑
export const addMusicToAlbum = async (albumId, musicIds) => {
  try {
    const response = await request({
      url: `/album/${albumId}/music`,
      method: 'POST',
      data: { musicIds },
    })
    if (response.success) {
      ElMessage.success('添加音乐到专辑成功')
    } else {
      ElMessage.error(response.message || '添加音乐到专辑失败')
    }
    return response
  } catch (error) {
    ElMessage.error('添加音乐到专辑失败')
    return { success: false, message: error.message }
  }
}

// 获取用户专辑列表
export const getUserAlbums = async (userId) => {
  try {
    const response = await request({
      url: `/album/user/${userId}`,
      method: 'GET',
    })
    return response
  } catch (error) {
    ElMessage.error('获取用户专辑列表失败')
    return { success: false, message: error.message }
  }
}
